##*********************************************************************************
#  Copyright(C), TMR.Nic @ AIMCNT
#  FileName:  Send2AdminDlg
#  Author:  TMR.Nic
#  Version:  1.1
#  Date:  2022-11-23
#  Description:  
#     收集NAS安装的ID信息，发送给管理员
#  History:
#     2023-01-30: 创建工程
#     2023-02-05: 完成数据传输功能，与服务器测试正常
#  
##*********************************************************************************

from PyQt6.QtWidgets import QDialog
from Send2AdminDlgForm import Ui_Dialog
import socket
import win32api, win32con

# ================ Info Dlg   ==================
def Toast(title, content):
    win32api.MessageBox(None,content,title,win32con.MB_OK)

# ================ 发送ID对话框类 ================
#  Send2AdminDlg 向管理员提交ID信息
# ================================================
class Send2AdminDlg(QDialog, Ui_Dialog):
    def __init__(self):
        super(Send2AdminDlg, self).__init__()    
        self.setupUi(self)
        self.host = '127.0.0.1'
        self.port = 6658        # 目前使用测试端口

    # 建立网络连接，获取Admin联系方式，完成初始化
    def init(self):
        server_addr = (self.host, self.port)
        self.tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.tcp_socket.connect(server_addr)
        send_data = "number".encode(encoding="utf-8")     # 发送number指令获取管理员手机号
        self.tcp_socket.send((send_data))
        rcv_data = self.tcp_socket.recv(64)
        admin_phone = rcv_data.decode(encoding='utf-8')
        self.label_admin_phone.setText(admin_phone)
    
    # 将ID信息写入相应的编辑框，禁止用户修改
    def write_id(self, userid):
        self.lineEdit_nasid.setText(userid)
        self.lineEdit_nasid.setEnabled(False)

    # 将ID信息上传NAS管理员
    def sendID(self):
        str_name = self.lineEdit_name.text()
        str_num = self.lineEdit_number.text()
        str_wxnum = self.lineEdit_wxnum.text()
        str_userid = self.lineEdit_nasid.text()

        if len(str_name)<=0:    # 检查各项是否为空
            Toast("警告", "姓名不能为空")
            return
        if len(str_num)<=0:
            Toast("警告", "学号不能为空")
            return
        if len(str_wxnum)<=0:
            Toast("警告", "微信号不能为空")
            return
        
        content = str_name+","+str_num+","+str_userid+","+str_wxnum+";"     # 构建发送信息
        send_data = content.encode(encoding="utf-8")        # 信息编码
        self.tcp_socket.send("upload_id".encode(encoding = "utf-8"))
        self.tcp_socket.send((send_data))
        rcv_data = self.tcp_socket.recv(64)
        if rcv_data.decode(encoding='utf-8') == "upload finished":
            Toast("提示", "信息已发送给NAS管理员，请等待授权处理……")
            self.tcp_socket.send("disconnect".encode(encoding = "utf-8"))
            self.tcp_socket.close()
            self.close()
        else:
            Toast("提示", "发送失败，请检查网络并重新发送。")

        